import os, time, click, requests, random
from multiprocessing import Process, Pool
from app.models import User, Profile
from app.extensions import db
# from app.spider import Spider
from app.lsol import Spider


def register(app):
    @app.cli.command(short_help='init app.')
    @click.option('--username', prompt=True, help='The username used to login.')
    @click.option('--password', prompt=True, hide_input=True,
                  confirmation_prompt=True, help='The password used to login.')
    def init(username, password):
        click.echo('init app, create admin account.')
        admin = User(username=username, password=password)
        db.session.add(admin)
        db.session.commit()
        click.echo('success created account, username:{}'.format(username))

    @app.cli.command(short_help='faker categorys data...')
    def fake_categorys():
        from app.fakes import fake_categorys
        click.echo('生成栏目数据...')
        fake_categorys()
        click.echo('完成')

    @app.cli.command(short_help='爬取百科')
    def fetchBkA():
        page = 1
        url = 'https://www.qiushibaike.com/hot/page/{page}/'
        try:
            res = requests.get(url.format(page=page))
        except requests.exceptions.ConnectionError:
            click.echo('网络问题')

        print(res)

    @app.cli.command(short_help='抓取爱问人')
    def fetchAsk():
        spider = Spider()
        spider.run()

    @app.cli.command(short_help='多进程')
    def mu():
        def worker(interval, i):
            for i in range(5):
                print('P{}.The time is {}'.format(i, time.ctime()))
                time.sleep(interval)

        for i in range(5):
            p = Process(target=worker, args=(1, i))
            p.start()
            print('P.pid:{}. P.name:{}. P.is_alive:{}'.format(p.pid, p.name, p.is_alive()))

    @app.cli.command(short_help='批量下载丽水在线视频')
    def lsol_video():
        spider = Spider()
        spider.run()









